const path = require('path');

const qiniu = require('qiniu');

const { QN_AK, QN_SK, QN_SCOPE } = require('@config/config.default');

const {
  goodsUnSupport,
  goodsUploadErr,
  goodsRemoveErr,
  goodsRestoreErr,
  goodsUpdateErr,
  goodsGetListErr,
  goodsAddListErr
} = require('@constant/error.type');

const { controller, emit } = require('@utils/tools');

const {
  goodsAdd,
  goodsRemove,
  goodsRestore,
  goodsUpdate,
  goodsGetList,
} = require('./goods.service');

module.exports = {
  async upload(ctx) {
    const { file } = ctx.request.files;

    const fileTypes = ['image/jpeg', 'image/png'];

    if (file) {
      if (!fileTypes.includes(file.mimetype)) {
        return ctx.app.emit('error', goodsUnSupport, ctx);
      }

      ctx.app.emit('success', { goods_img: path.basename(file.filepath) }, ctx);
    } else {
      return ctx.app.emit('error', goodsUploadErr, ctx);
    }
  },

  async create(ctx) {
    const res = await controller(ctx.request.body, goodsAdd);

    emit(ctx, res, res, goodsAddListErr);
  },

  async update(ctx) {
    const res = await controller(ctx.request.body, goodsUpdate);

    emit(ctx, res, ctx.request.body, goodsUpdateErr);
  },

  async restore(ctx) {
    const params = { id: ctx.request.body.id };

    const res = await controller(params, goodsRestore);

    emit(ctx, res, params, goodsRestoreErr);
  },

  async remove(ctx) {
    const params = { id: ctx.request.params.id };

    const res = await controller(params, goodsRemove);

    emit(ctx, res, params, goodsRemoveErr);
  },

  async getList(ctx) {
    const res = await controller(ctx.query, goodsGetList);

    emit(ctx, res, res, goodsGetListErr);
  },

  async getQnToken(ctx) {
    try {
      const options = {
        scope: QN_SCOPE,
      };

      const mac = new qiniu.auth.digest.Mac(QN_AK, QN_SK);

      const putPolicy = new qiniu.rs.PutPolicy(options);

      const uploadToken = putPolicy.uploadToken(mac);

      emit(ctx, uploadToken, { uploadToken }, {});
    } catch (error) {
      console.log(error, 'error');
    }
  },
};
